package org.dromara.pay.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.business.constant.BusinessConstants;
import org.dromara.business.domain.*;
import org.dromara.business.mapper.AdvertisingMapper;
import org.dromara.business.mapper.BusinessInformationMapper;
import org.dromara.business.service.*;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.websocket.utils.WebSocketUtils;
import org.dromara.pay.domain.TopUp;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 充值成功回调处理器
 *
 * @author zlj
 * @since 2024/5/16
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BusinessHandleService {

    private final GoodsService goodsService;
    private final ScheduledExecutorService scheduledExecutorService;
    private final BusinessConfigService businessConfigService;
    private final RoomService roomService;
    private final UserService userService;
    private final UserFlowingService userFlowingService;
    private final BusinessInformationMapper businessInformationMapper;




    /**
     * 支付业务处理
     *
     * @param topUp 订单信息
     */
    public void businessHandle(TopUp topUp) {
        String orderType = topUp.getOrderType();
        //订单orderId
        String orderJson = topUp.getOrderJson();
        Long userId = topUp.getCreateBy();
        User user = userService.getById(userId);
        //是购买会员
        if (ObjectUtil.equals(orderType, "goods")) {
            processMemberPurchase(user, orderJson, topUp);
            try {
                scheduledExecutorService.schedule(() -> {
                    WebSocketUtils.sendMessage(UserConstants.SUPER_ADMIN_ID, "用户:"+user.getNickName()+"购买会员");
                }, 0, TimeUnit.SECONDS);
            }catch ( Exception e){
                log.warn("充值记录{}发送信息失败",topUp.getOrderJson());
                log.warn( e.getMessage(), e);

            }

        }
        // 是发布广告
        else if (ObjectUtil.equals(orderType, "advertising")) {
            publishAdvertisement(user, orderJson, topUp);
            try {
                scheduledExecutorService.schedule(() -> {
                    WebSocketUtils.sendMessage(UserConstants.SUPER_ADMIN_ID, "用户:"+user.getNickName()+"发布广告");
                }, 0, TimeUnit.SECONDS);
            }catch ( Exception e){
                log.warn("充值记录{}发送信息失败",topUp.getOrderJson());
                log.warn( e.getMessage(), e);

            }

        }
    }

    /**
     * 发布广告处理
     *
     * @param user
     * @param orderJson
     * @param topUp
     */
    private void publishAdvertisement(User user, String orderJson, TopUp topUp) {
//        QueryWrapper<Advertising> queryWrapper = Wrappers.query();
//
//        queryWrapper.eq("create_by", user.getUserId())
//            .orderByDesc("create_time") // 按照创建时间降序排序
//            .last("LIMIT 1");
//
//        List<Advertising> advertisings = advertisingMapper.selectList(queryWrapper);
//
//        if (advertisings.size() < 0) {
//            return;
//        }
        User user1 = userService.selectByProxyRegion(orderJson);


        if (ObjectUtil.isNotNull(user1)) {
            // 返回佣金
            BigDecimal commission = userFlowingService.earnPoints(user.getCity(), topUp.getTotal());
            userFlowingService.addAmount(user1.getUserId(), commission, BusinessConstants.FLOWING_TYPE_SIGN, user.getUserId());
        }

    }

    /**
     * @param user
     * @param orderJson
     */
    private void processMemberPurchase(User user, String orderJson, TopUp topUp) {
        BusinessConfig businessConfig = businessConfigService.getById(orderJson);
        // 修改用户新增刷新次数和发布次数
        if (!"".equals(orderJson) && orderJson != null) {
            if (businessConfig != null) {

                String remark = businessConfig.getRemark();
                String[] split = remark.split("-");
                if (split.length > 1 && isNumeric(split[0]) && isNumeric(split[1])) {
                    int hyNumber = Integer.parseInt(split[0]);
                    int refreshTimes = Integer.parseInt(split[1]);
                    user.setHyNumber(hyNumber);
                    user.setRefreshTimes(refreshTimes);
                }
                int daysToAdd = 0;

                if (1 == businessConfig.getSortNo()) {
                    daysToAdd = 7;
                } else if (2 == businessConfig.getSortNo()) {
                    daysToAdd = 30;
                } else if (3 == businessConfig.getSortNo()) {
                    daysToAdd = 365;
                }
                // 计算当前时间加上指定天数后的时间
                LocalDateTime currentTime = LocalDateTime.now();
                LocalDateTime newTime = currentTime.plusDays(daysToAdd);
                Date gqTime = Date.from(newTime.atZone(ZoneId.systemDefault()).toInstant());
                user.setGqTime(gqTime);
                user.setVip(businessConfig.getSortNo() + "");
                user.setVipTime(new Date());
                //删除之前所有的发布信息
                deleteAllPreviousPosts(user.getUserId());
                boolean b = userService.updateById(user);
            }
        }
        //查询我所在城市的代理
        User user1 = userService.selectByProxyRegion(user.getCity());
        if (ObjectUtil.isNotNull(user1)) {
            // 返回佣金
            BigDecimal commission = userFlowingService.earnPoints(user.getCity(), topUp.getTotal());
            userFlowingService.addAmount(user1.getUserId(), commission, BusinessConstants.FLOWING_TYPE_SIGN, user.getUserId());
        }


    }

    /**
     * 删除之前用户发布的所有信息
     *
     * @param userId
     */
    private void deleteAllPreviousPosts(Long userId) {
        // 创建一个QueryWrapper实例
        QueryWrapper<BusinessInformation> queryWrapper = Wrappers.query();
        // 设置删除条件：expiration_date小于当前时间
        queryWrapper.eq("create_by", userId);
        // 执行删除操作
        int deleteCount = businessInformationMapper.delete(queryWrapper);
        log.warn("用户{}成为会员删除了{}条信息", userId, deleteCount);
    }


    /**
     * 退款业务处理
     *
     * @param topUp 订单信息
     */
    public void businessRefundHandle(TopUp topUp) {
        //
        String orderType = topUp.getOrderType();
        String orderJson = topUp.getOrderJson();
        Long userId = topUp.getCreateBy();
        if (ObjectUtil.equals(orderType, "goods")) {
            // 1类型业务处理
            Goods goods = goodsService.getById(Long.valueOf(orderJson));
            if (ObjectUtil.isNotNull(goods)) {
                goodsService.removeById(goods);
                scheduledExecutorService.schedule(() -> {
                    WebSocketUtils.sendMessage(UserConstants.SUPER_ADMIN_ID, "订单" + orderJson + "退款已到账");
                }, 0, TimeUnit.SECONDS);
                roomService.send(0L, goods.getCreateBy(), "您发布的任务<" + goods.getName() + ">已退款,请确认");
            }
        } else if (ObjectUtil.equals(orderType, "2")) {
            // 2类型业务处理
        }
    }

    private boolean isNumeric(String str) {
        try {
            // 使用 BigDecimal 的构造函数，它可以处理整数和小数
            new BigDecimal(str);
            return true;
        } catch (NumberFormatException e) {
            // 捕获异常，表示字符串不是有效的数字格式
            return false;
        }
    }
}
